package com.truthbean.jeetb.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.sd4324530.fastweixin.api.response.BaseResponse;
import com.github.sd4324530.fastweixin.util.JSONUtil;
import com.github.sd4324530.fastweixin.util.NetWorkCenter;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by TruthBean on 2016-10-09 15:35.
 */
public class NetWorkUtils {
    private static final Logger logger = LogManager.getLogger(NetWorkUtils.class.getName());

    public static JSONObject netGet(String url) {
        logger.info("netGet url: " + url);
        try {
            BaseResponse response = NetWorkCenter.get(url);
            if (Objects.equals(response.getErrcode(), "0")) {
                JSONObject object = JSON.parseObject(response.getErrmsg());
                logger.info("response result: " + object.toJSONString());
                if (object.containsKey("code")) {
                    Object code = object.get("code");
                    if (code instanceof String && code.equals("0")) {
                        return object;
                    }
                }
            }
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        }

        return null;
    }

    public static JSONObject netPost(String url, String paramData) {
        logger.info("netPost url: " + url);
        try {
            BaseResponse response = NetWorkCenter.post(url, paramData);
            if (response.getErrcode() == null || "0".equals(response.getErrcode())) {
                JSONObject object = JSON.parseObject(response.getErrmsg());
                logger.info("response result: " + object.toJSONString());
                if (object.containsKey("code")) {
                    Object code = object.get("code");
                    if (code instanceof String && code.equals("0")) {
                        return object;
                    }
                }
            }
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        }
        return null;
    }

    public static JSONObject netPost2(String url, String paramData) {
        logger.info("netPost url: " + url);
        try {
            BaseResponse response = NetWorkCenter.post(url, paramData);
            if (response.getErrcode() == null || "0".equals(response.getErrcode())) {
                JSONObject object = JSON.parseObject(response.getErrmsg());
                logger.info("response result: " + object.toJSONString());
                return object;
            }
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        }
        return null;
    }

    public static Map<String, Object> doGet(String url) {
        try {
            BaseResponse response = NetWorkCenter.get(url);
            return JSONUtil.toMap(response.getErrmsg());
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        }
    }

    public static Map<String, Object> doPost(String url, Map<String, Object> params) {
        try {
            String json = JSONUtil.toJson(params);
            BaseResponse response = NetWorkCenter.post(url, json);
            return JSONUtil.toMap(response.getErrmsg());
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        }
    }

    public static String doHttpGet(String url){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpGet.setHeader("Cookie", "_user_behavior_=d2b32675-685f-44c9-af6a-3dd0c5a43476");
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
            httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpGet.setHeader("Accept-Encoding", "gzip, deflate, sdch");
            httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");

            logger.info("Executing request " + httpGet.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if(status >= 200 && status <300){
                        HttpEntity entity = response.getEntity();
                        if(entity != null){
                            return EntityUtils.toString(entity);
                        } else
                            return null;
                    } else {
                        throw new ClientProtocolException(response.getStatusLine().toString());
                    }
                }
            };
            return httpclient.execute(httpGet, responseHandler);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
